import axios from 'axios';
import {Message, MessageBox} from "element-ui";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const service = axios.create({
  // baseURL: process.env.BASE_URL,
  // baseURL: "http://localhost:8081",
  baseURL: '/dev-api',
  timeout: 5000
});

//请求拦截器
service.interceptors.request.use(request => {
  NProgress.start();  //显示进度条
  return request
});

//响应拦截器
service.interceptors.response.use(response => {
    const res = response.data
    if (res === 0 || res.code === 100 || res.code === 200 || res.code === 500) {
      NProgress.done(); //  关闭进度条
      return res
    } else {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 2 * 1000
      })
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      NProgress.done(); //  关闭进度条
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    NProgress.done(); //  关闭进度条
    return Promise.reject(error)
  });


export default service;
